package com.mxpio.erp.plan.controller;


import com.mxpio.erp.common.enums.NoticeStatusEnums;
import com.mxpio.erp.common.jpa.model.Notice;
import com.mxpio.erp.common.order.policy.NoticeContext;
import com.mxpio.erp.common.order.service.NoticeService;
import com.mxpio.erp.common.plan.entity.ODReceivingNotice;
import com.mxpio.erp.common.plan.service.ODReceivingNoticeService;
import com.mxpio.erp.common.technology.service.ItemService;
import com.mxpio.erp.common.vo.OrderExcuteVo;
import com.mxpio.erp.plan.policy.impl.DefaultODNoticePolicy;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.jpa.query.Criteria;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.List;

@Tag(name = "ODReceivingNoticeController", description = "组织需求接料通知单数据接口")
@RestController
@RequestMapping("/erp/plan/odrec/")
public class ODReceivingNoticeController {

    @Autowired
    private ODReceivingNoticeService service;

    @Autowired
    private NoticeService noticeService;

    @Autowired
    private ItemService itemService;

    @GetMapping("list")
    @Operation(summary = "接料通知单列表", description = "获取接料通知单列表（无分页）", method = "GET")
    public Result<List<ODReceivingNotice>> list(@Parameter(description="查询参数") Criteria criteria) throws UnsupportedEncodingException {
        List<ODReceivingNotice> notice = service.list(ODReceivingNotice.class, criteria);
        return Result.OK(notice);
    }

    @GetMapping("page")
    @Operation(summary = "接料通知单列表", description = "获取接料通知单列表（分页）", method = "GET")
    public Result<Page<ODReceivingNotice>> page(@Parameter(description="查询参数") Criteria criteria, @Parameter(description="每页条数")Integer pageSize, @Parameter(description="页号")Integer pageNo) throws UnsupportedEncodingException {
        Pageable page = PageRequest.of(pageNo-1, pageSize);
        Page<ODReceivingNotice> notice = service.listPage( page, criteria);
        return Result.OK(notice);
    }

    @GetMapping("list/{noticeNo}")
    @Operation(summary = "根据noticeNo获取接料通知单", description = "根据noticeNo获取接料通知单", method = "GET")
    public Result<ODReceivingNotice> getById(@Parameter(description="业务单号") @PathVariable(name = "noticeNo", required = true) String noticeNo) {
        ODReceivingNotice notice = service.getById(ODReceivingNotice.class, noticeNo);
        return Result.OK(notice);
    }

    /*@RequestMapping("save")
    @Operation(summary = "保存接料通知单", description = "保存接料通知单")//资产系统 到货通知单 增加新增录入功能， 接口
    public Result<ODReceivingNotice> save(@RequestBody ODReceivingNotice notice) {
        if (CrudType.SAVE.equals(notice.getCrudType())){
            notice.setNoticeDate(new Date());
            notice.setAccessType(OrderEnums.AccessType.IN.getCode());// 根据 组织需求订单执行生成通知单逻辑 set对应字段值
            notice.setPickingType(NoticeStatusEnums.NoticeType.PO_IN.getCode());
            notice.setNoticeStatus(NoticeStatusEnums.NoticeStatus.DRAFT.getStatusCode());//默认草稿
            List<ODReceivingNoticeLine> receivingOrderLines = notice.getOdReceivingNoticeLines();
            for(ODReceivingNoticeLine line : receivingOrderLines) {
                Item item = itemService.getById(Item.class,line.getItemCode());
                line.setItemName(item.getItemName());
                line.setItemSpec(item.getItemSpec());
                line.setUnitCode(item.getUnitCode());
            }
        }else{
            List<ODReceivingNoticeLine> receivingOrderLines = notice.getOdReceivingNoticeLines();
            for(ODReceivingNoticeLine line : receivingOrderLines) {
                if (CrudType.SAVE.equals(line.getCrudType())){
                    Item item = itemService.getById(Item.class,line.getItemCode());
                    line.setItemName(item.getItemName());
                    line.setItemSpec(item.getItemSpec());
                    line.setUnitCode(item.getUnitCode());
                }
            }
        }
        service.save(notice,new SmartCrudPolicyAdapter(){
            @Override
            public boolean beforeInsert(CrudContext context) {
                Object o = context.getEntity();
                if(o instanceof ODReceivingNoticeLine){
                    ODReceivingNotice oDReceivingNotice = context.getParent();
                    ((ODReceivingNoticeLine) o).setNoticeNo(oDReceivingNotice.getNoticeNo());
                }
                return true;
            }
        });
        return Result.OK(notice);
    }*/


    @DeleteMapping("remove/{noticeNos}")
    @Operation(summary = "根据noticeNo删除接料通知单", description = "删除接料通知单", method = "DELETE")
    public Result<ODReceivingNotice> remove(@Parameter(description="业务单号，多个单号用英文逗号分隔") @PathVariable(name = "noticeNos", required = true) String noticeNos) {
        String[] noticeNo = noticeNos.split(",");
        for(String key : noticeNo){
            service.delete(ODReceivingNotice.class, key);
        }
        return Result.OK();
    }

    @RequestMapping("execute/{noticeNo}")
    @Operation(summary = "通知单执行", description = "通知单执行")
    @Transactional
    public Result<Object> excute(@PathVariable(name = "noticeNo", required = true) String noticeNo,
                                 @RequestBody OrderExcuteVo orderExcuteVo) {
        ODReceivingNotice notice = service.getById(ODReceivingNotice.class, noticeNo);
        /*List<OrderExcuteLineVo> lines = orderExcuteVo.getLines();
        for (OrderExcuteLineVo vo:lines){//资产 批次号生成逻辑迁移至 AbstractNoticePolicy 类中的apply方法 生成
            if (StringUtils.isEmpty(vo.getLotNo())){
                BizNoticeType bizNoticeType = JpaUtil.linq(BizNoticeType.class).idEqual("Q01").findOne();
                StringBuffer expression = new StringBuffer(bizNoticeType.getTypePrefix());
                for(int i=0 ;i < bizNoticeType.getTypeSize(); i++){
                    expression.append("#");
                }
                SnRuleService snRuleService = SpringUtil.getBean(SnRuleService.class);
                String bizNo = snRuleService.execute(expression.toString(), null).toString();

                Lot lot = new Lot();
                String lotNoEx = "";
                lotNoEx = bizNo + "-" + vo.getBizOrderlineNo() + "####";
                lot.setLotNo(snRuleService.execute(lotNoEx, null).toString());
                lot.setLotStatus("1");
                JpaUtil.save(lot);
                vo.setLotNo(lot.getLotNo());
            }
        }*/
        if (notice.getNoticeStatus().equals(NoticeStatusEnums.NoticeStatus.CONFIRM.getStatusCode())){
            return Result.error("单据状态已发生变化，已确认状态单据不允许重复确认！");
        }
        NoticeContext context = noticeService.execute(notice, new DefaultODNoticePolicy(orderExcuteVo.getLines()));
        if(CollectionUtils.isEmpty(context.getErrors())) {
            return Result.OK();
        }else {
            return Result.error(context.getErrors().get(0));
        }
    }

    @PutMapping("reject/{noticeNo}")
    @Operation(summary = "拒绝通知单", description = "拒绝通知单", method = "PUT")
    public Result<? extends Notice> close(@Parameter(description="通知单号") @PathVariable(name = "noticeNo", required = true) String noticeNo) {
        ODReceivingNotice notice = service.getById(ODReceivingNotice.class,noticeNo);
        return noticeService.updateNoticeStatus(notice, NoticeStatusEnums.NoticeStatus.REJECT);
    }

    @PutMapping("commit/{noticeNo}")
    @Operation(summary = "提交通知单", description = "提交通知单", method = "PUT")
    @Transactional
    public Result<? extends Notice> commit(@Parameter(description="通知单号") @PathVariable(name = "noticeNo", required = true) String noticeNo) {
        ODReceivingNotice notice = service.getById(ODReceivingNotice.class,noticeNo);
        if (!StringUtils.equals(notice.getNoticeStatus(),NoticeStatusEnums.NoticeStatus.DRAFT.getStatusCode())){
            return Result.error("仅草稿状态的通知单允许提交操作");
        }
        return noticeService.updateNoticeStatus(notice, NoticeStatusEnums.NoticeStatus.CREATE);//更新为开立状态，相当于待审核
    }

    @GetMapping("listbynos/{noticeNos}")
    @Operation(summary = "根据noticeNos获取对应组织需求接料通知单及明细", description = "根据noticeNos获取组织需求接料通知单及明细", method = "GET")
    public Result<List<ODReceivingNotice>> getByIds(@PathVariable(name = "noticeNos", required = true) String noticeNos) {
        return service.listByIds(noticeNos);
    }
}
